using System.Collections;

using LocalBoard.Domain;
using LocalBoard.Controller;

namespace LocalBoard.Web.UserControls
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;

	/// <summary>
	///		Summary description for ClubInformation.
	/// </summary>
	public partial class ClubInformation : ClubUserControl
	{
		public const string MODE_CREATE = "CREATE";
		public const string MODE_CHANGE = "CHANGE";
		public const string MODE_DELETE = "DELETE";


		DataSet XmlDataSet;
		DataTable XmlDataTable;
		bool isEditing = false;

		private string _mode = MODE_CREATE;
		public string Mode
		{
			get {return _mode;}
			set {_mode = value;}
		}
		private bool _fixClubType;
		public bool FixClubType
		{
			get {return _fixClubType;}
			set {_fixClubType = value;}
		}
		private string _fixedClubType = "";
		public string FixedClubType
		{
			get {return _fixedClubType;}
			set {_fixedClubType = value;}
		}
		public Label ClubId
		{
			get {return clubId;}
			set {clubId = value;}
		}
		private readonly AdminController _adminController = new AdminController(Global.AccessorFactory);


		protected void Page_Load(object sender, System.EventArgs e)
		{
			if(_mode.ToUpper() == MODE_CREATE)
			{
				change.Visible = false;
				delete.Visible = false;
			}
			if(_mode.ToUpper() == MODE_CHANGE)
			{
				create.Visible = false;
				delete.Visible = false;
			}
			if(_mode.ToUpper() == MODE_DELETE)
			{
				create.Visible = false;
			}

			//			if(_mode.ToUpper() == MODE_CHANGE)
			//				InitializeClubInformation();
			//
			if(!IsPostBack)
			{
				InitializeClubCategoryList();
				InitializeClubType();
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);
			this.DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndexChanged);
			this.DataGrid1.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_CancelCommand);
			this.DataGrid1.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_EditCommand);
			this.DataGrid1.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_UpdateCommand);
			this.DataGrid1.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_DeleteCommand);
		}
		#endregion

		#region Helper
		private void InitializeClubCategoryList()
		{
			clubCategory.Items.Clear();
			foreach(DictionaryEntry item in new AdminController(Global.AccessorFactory).GetAllClubCategories())
			{
				clubCategory.Items.Add(new ListItem(item.Value.ToString(), item.Key.ToString()));
			}
			//			if(clubCategory.Items.Count > 0)
			//				clubCategory.SelectedIndex = 1;
		}

		private void InitializeClubType()
		{
			if(_fixClubType)
				clubTypeRow.Visible = false;
			clubType.DataSource = Enum.GetNames(typeof(ClubType));
			DataBind();
			foreach(ListItem item in clubType.Items)
			{
				if(_fixClubType && item.Value == _fixedClubType)
				{
					item.Selected = true;
					return;
				}
				if(item.Value == ClubType.Public.ToString())
				{
					item.Selected = true;
					return;
				}
			}
		}

		public void InitializeClubInformation()
		{
			if(GetClubId() == 0)
				return;
			FillInClubSetting(GetClub(GetClubId()));
		}

		private Club GetClub(int clubId)
		{
			Club club = null;
			if(clubId > 0)
				club = _adminController.GetClub(clubId);
			return club;
		}

		private void FillInClubSetting(Club club)
		{
			if(club == null)
				return;
			clubName.Text = club.Name;
			uniqueName.Text = club.UniqueName;
			SetClubCategoryList(club);
			description.Text = club.Description;
			SetClubTypeList(club);
		}

		private void SetClubCategoryList(Club club)
		{
			//			clubCategory.DataSource = Enum.GetNames(typeof(ClubType));
			//			DataBind();
			foreach(ListItem item in clubCategory.Items)
			{
				if(item.Value == club.CategoryId.ToString())
					item.Selected = true;
				else
					item.Selected = false;
			}
		}

		private void SetClubTypeList(Club club)
		{
			clubType.DataSource = Enum.GetNames(typeof(ClubType));
			DataBind();
			foreach(ListItem item in clubType.Items)
			{
				if(item.Value == club.ClubType.ToString())
					item.Selected = true;
			}
		}

		private int GetClubId()
		{
			return GetIntFromString(clubId.Text);
		}

		private int GetIntFromString(string value)
		{
			if(value == null || value.Length == 0)
				return 0;
			return Convert.ToInt32(value);
		}
		#endregion

		protected void NewFileButton_Click(object sender, System.EventArgs e)
		{
			Message.Text = "&nbsp;";
			string NewFileName = LoadXmlTextBox.Text;
			bool fileExist = false;

			string path = HttpContext.Current.Server.MapPath("Forms/" + NewFileName);
			System.IO.FileInfo fileName=new System.IO.FileInfo(path);
			try
			{
				if (fileName.Exists)
				{
					fileExist = true;
				}
			}
			catch
			{
				Message.Text = "The Xml file is already exist. Can not create a new file.";
			}
				
			if(NewFileName.Length >= 5 && !fileExist)
			{
				if(NewFileName.Substring(NewFileName.Length - 4, 4) == ".xml")
				{
					try
					{
						DataTable NewXmlTable = new DataTable("Fields");
						DataSet NewXmlFile = new DataSet();
						NewXmlTable.Columns.Add("Control");
						NewXmlTable.Columns.Add("Data");
						NewXmlTable.Columns.Add("Required");
						NewXmlTable.Columns.Add("Order");
						NewXmlTable.Columns.Add("Label");
						NewXmlTable.Columns.Add("Text");
						DataRow NewXmlRow = NewXmlTable.NewRow();
						NewXmlRow[NewXmlTable.Columns[0].Caption] = "TextBox";
						NewXmlRow[NewXmlTable.Columns[1].Caption] = "Other";
						NewXmlRow[NewXmlTable.Columns[2].Caption] = "Yes";
						NewXmlRow[NewXmlTable.Columns[3].Caption] = "";
						NewXmlRow[NewXmlTable.Columns[4].Caption] = "";
						NewXmlRow[NewXmlTable.Columns[5].Caption] = "";
						NewXmlTable.Rows.Add(NewXmlRow);
						NewXmlFile.Tables.Add(NewXmlTable);
						NewXmlFile.WriteXml
							(HttpContext.Current.Server.MapPath("Forms/" + NewFileName));
						LoadXml();
					}
					catch
					{
						Message.Text = "Could not create the Xml file";
					}
				}
				else 
				{
					Message.Text = "Could not create the Xml file";
				}
			}
			else 
			{
				if(fileExist)
					Message.Text = "Duplicate file is already exist.";
				else
					Message.Text = "File length should be longer than 5 digits.";
			}
		}

		private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			CheckIsEditing(e.CommandName);
		}

		private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			if (!isEditing && XmlDataTable.Rows.Count > 1) 
			{
				XmlDataTable.Rows.RemoveAt(e.Item.DataSetIndex);
				XmlDataSet.WriteXml(HttpContext.Current.Server.MapPath("Forms/" + LoadXmlTextBox.Text));
				DataGrid1.CurrentPageIndex = 0;
				DataGrid1.EditItemIndex = -1;
				BindGrid();
			}
		}

		private void DataGrid1_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			if (!isEditing) 
			{
				DataGrid1.EditItemIndex = e.Item.ItemIndex;
				BindGrid();
			}
		}

		private void DataGrid1_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			DataGrid1.EditItemIndex = -1;
			BindGrid();
			AddingNew = false;
		}

		private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
		{
			if (!isEditing) 
			{
				DataGrid1.EditItemIndex = -1;
				DataGrid1.CurrentPageIndex = e.NewPageIndex;
				BindGrid();
			}
		}

		protected void AddRowButton_Click(object sender, System.EventArgs e)
		{
			CheckIsEditing("");
			if (!isEditing) 
			{
				AddingNew = true;
				DataRow r = XmlDataTable.NewRow();
				for (int i=2; i<XmlDataTable.Columns.Count; i++) 
				{
					r[XmlDataTable.Columns[i].Caption] = "";
				}
				r[XmlDataTable.Columns[0].Caption] = "TextBox";
				r[XmlDataTable.Columns[1].Caption] = "Other";
				r[XmlDataTable.Columns[2].Caption] = "Yes";
				XmlDataTable.Rows.Add(r);
				XmlDataSet.WriteXml(HttpContext.Current.Server.MapPath("Forms/" + LoadXmlTextBox.Text));
				int recordCount = XmlDataSet.Tables["Fields"].Rows.Count;
				if (recordCount > 1)
					recordCount--;
				DataGrid1.CurrentPageIndex = recordCount/DataGrid1.PageSize;
				DataGrid1.EditItemIndex = recordCount%DataGrid1.PageSize;
				BindGrid();
			}
		}

		private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			DataRow row = XmlDataTable.Rows[e.Item.DataSetIndex];
			for (int i=3; i<XmlDataTable.Columns.Count; i++) 
			{
				int j = i + 2;
				TextBox t = (TextBox)e.Item.Cells[j].Controls[0];
				row[XmlDataTable.Columns[i].Caption] = t.Text;
			}
    
			DropDownList d1 = (DropDownList)e.Item.Cells[2].FindControl("ddlControl");
			row[XmlDataTable.Columns[0].Caption] = d1.SelectedItem.Text;
			DropDownList d2 = (DropDownList)e.Item.Cells[3].FindControl("ddlData");
			row[XmlDataTable.Columns[1].Caption] = d2.SelectedItem.Text;
			DropDownList d3 = (DropDownList)e.Item.Cells[4].FindControl("ddlRequired");
			row[XmlDataTable.Columns[2].Caption] = d3.SelectedItem.Text;
    
			XmlDataSet.WriteXml(HttpContext.Current.Server.MapPath("Forms/" + LoadXmlTextBox.Text));
			DataGrid1.EditItemIndex = -1;
			if (AddingNew) 
			{
				DataGrid1.CurrentPageIndex = 0;
				AddingNew = false;
			}
			DataGrid1.EditItemIndex = -1;
			BindGrid();
		}

		protected void LoadXmlButton_Click(object sender, System.EventArgs e)
		{
			LoadXml();
		}

		#region FormGeneration related

		void LoadXml() 
		{
			Message.Text = "";
			
			AddRowButton.Visible = false;
			DataGrid1.Visible = false;
			try
			{
				XmlDataSet = new DataSet();
				XmlDataSet.ReadXml(HttpContext.Current.Server.MapPath("Forms/" + LoadXmlTextBox.Text),
					XmlReadMode.InferSchema);
				XmlDataTable = new DataTable();
				XmlDataTable = XmlDataSet.Tables["Fields"];
				AddRowButton.Visible = true;
				DataGrid1.Visible = true;
				DataGrid1.CurrentPageIndex = 0;
				BindGrid();
			}
			catch
			{
				Message.Text = "Could not load the Xml file";
			}
		}
    
		void BindGrid() 
		{
			DataGrid1.DataSource = XmlDataTable;
			DataGrid1.DataBind();
			AddRowButton.Visible = true;
			previewLink.NavigateUrl = "~/PreviewClubForm.aspx?formName="+LoadXmlTextBox.Text;
			previewLink.Visible = true;
		}
    
		void CheckIsEditing(string commandName) 
		{
			if (DataGrid1.EditItemIndex != -1) 
			{
				if (commandName != "Cancel" && commandName != "Update") 
				{
					Message.Text = "Your changes have not been saved yet. "
						+ "Please press update to save your changes, or cancel "
						+ "to discard your changes, before selecting another item.";
					isEditing = true;
				}
			}
		}
		protected bool AddingNew 
		{
			get 
			{
				object o = ViewState["AddingNew"];
				return (o == null) ? false : (bool)o;
			}
			set 
			{
				ViewState["AddingNew"] = value;
			}
		}
		#endregion

		private void createJoinResultFile(string uniqueName)
		{
			try
			{
				DataTable NewXmlTable = new DataTable("Result");
				DataSet NewXmlFile = new DataSet();
				NewXmlFile.Tables.Add(NewXmlTable);
				NewXmlFile.WriteXml(HttpContext.Current.Server.MapPath("Results/" + uniqueName.Trim()+ Global.JOIN_FORM_RESULT));
			}
			catch
			{
				Message.Text = "Could not create the Xml file";
			}
		}

		#region Event handler
		protected void create_Click(object sender, EventArgs e)
		{
			AdminController controller = new AdminController(Global.AccessorFactory);
			//Note: we need to store a clubjoin form filename in Club Table. Or somewhere else.
			//Clubjoin form name can be accessed using LoadXmlTextBox.Text
			int clubId = controller.CreateClub(new Club(uniqueName.Text, clubName.Text, Convert.ToInt32(clubCategory.SelectedValue), description.Text, clubType.SelectedValue, null));
			//Create clubjoin form result xml file which is unique by club.
			createJoinResultFile(uniqueName.Text);
			ClubController clubController = new ClubController(clubId, Global.AccessorFactory);
			clubController.AssignClubManager(((ClubPrincipal)Page.User).UserProfile.Id);
			Response.Redirect(ClubPage.AddClubQueryStringToUrl("~/ManageClub.aspx", clubId));
		}

		protected void cancel_Click(object sender, EventArgs e)
		{
			Security.RedirectToHome();
		}

		protected void change_Click(object sender, EventArgs e)
		{
			Club club = GetClub(GetClubId());
			if(club != null)
			{
				club.Name = clubName.Text;
				club.UniqueName = uniqueName.Text;
				club.CategoryId = Convert.ToInt32(clubCategory.SelectedValue);
				club.Description = description.Text;
				club.ClubType = (ClubType)Enum.Parse(typeof(ClubType), clubType.SelectedValue, true);
				_adminController.UpdateClub(club);
				club = GetClub(GetClubId());
				FillInClubSetting(club);
			}
		}

		protected void delete_Click(object sender, EventArgs e)
		{
			if(GetClubId() == 0)
				return;
			_adminController.DeleteClub(GetClubId());
			Response.Redirect(Request.RawUrl);
		}
		#endregion
	}
}
